<template>
  <div class="document-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>知识库管理</h2>
          <el-button type="primary" @click="uploadDialogVisible = true">
            上传文档
          </el-button>
        </div>
      </template>

      <el-table :data="documentList" v-loading="loading" stripe style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="fileName" label="文件名" min-width="200" show-overflow-tooltip />
        <el-table-column prop="fileType" label="文件类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getFileTypeColor(row.fileType)">{{ row.fileType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="fileSize" label="文件大小" width="120">
          <template #default="{ row }">{{ formatFileSize(row.fileSize) }}</template>
        </el-table-column>
        <el-table-column prop="version" label="版本" width="100" />
        <el-table-column prop="createdAt" label="上传时间" width="180">
          <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewVersions(row)">版本历史</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: center"
      />
    </el-card>

    <el-dialog v-model="uploadDialogVisible" title="上传文档" width="500px">
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :on-change="handleFileChange"
        :limit="1"
        accept=".pdf,.doc,.docx,.xls,.xlsx,.txt"
        drag
      >
        <div class="el-upload__text">拖拽文件到此处或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">支持PDF、Word、Excel、TXT格式，单个文件不超过50MB</div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpload" :loading="uploading" :disabled="!selectedFile">
          确认上传
        </el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="versionDialogVisible" title="版本历史" width="70%">
      <el-table :data="versionList" v-loading="loadingVersions" stripe>
        <el-table-column prop="versionNumber" label="版本" width="100" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.isActive" type="success" size="small">启用中</el-tag>
            <el-tag v-else type="info" size="small">未启用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="文件名" min-width="200">
          <template #default="{ row }">{{ getDocumentFileName(row.documentId) }}</template>
        </el-table-column>
        <el-table-column prop="createdAt" label="上传时间" width="180">
          <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button 
              v-if="!row.isActive" 
              link 
              type="success" 
              @click="handleActivateVersion(row)"
              :loading="activatingVersionId === row.id"
            >
              应用
            </el-button>
            <el-button link type="primary" @click="handleSelectVersionForCompare(row)" :disabled="selectedVersions.length >= 2">
              选择对比
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="selectedVersions.length > 0" class="version-compare-section">
        <el-divider />
        <h4>已选择版本：</h4>
        <el-tag v-for="version in selectedVersions" :key="version.id" closable @close="handleRemoveVersionFromCompare(version)" style="margin-right: 10px">
          版本 {{ version.versionNumber }}
        </el-tag>
        <el-button v-if="selectedVersions.length === 2" type="primary" @click="handleCompareVersions" style="margin-left: 20px">
          对比版本
        </el-button>
      </div>
    </el-dialog>

    <el-dialog v-model="compareDialogVisible" title="版本对比" width="90%">
      <div v-if="compareResult" class="compare-result">
        <!-- 对比差异摘要 -->
        <el-card class="compare-summary" style="margin-bottom: 20px;">
          <template #header>
            <h3>对比结果摘要</h3>
          </template>
          <div class="differences-list">
            <div v-for="(diff, index) in compareResult.differences" :key="index" class="difference-item">
              {{ diff }}
            </div>
          </div>
        </el-card>
        
        <!-- 版本内容对比 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card>
              <template #header>
                <h4>版本 {{ compareResult.version1?.versionNumber }} 
                  <el-tag size="small" type="info">{{ formatDate(compareResult.version1?.createdAt) }}</el-tag>
                </h4>
              </template>
              <div class="version-content">
                <pre>{{ compareResult.version1?.extractedText || '无内容' }}</pre>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card>
              <template #header>
                <h4>版本 {{ compareResult.version2?.versionNumber }}
                  <el-tag size="small" type="info">{{ formatDate(compareResult.version2?.createdAt) }}</el-tag>
                </h4>
              </template>
              <div class="version-content">
                <pre>{{ compareResult.version2?.extractedText || '无内容' }}</pre>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { uploadDocument, getDocuments, deleteDocument, getVersions, compareVersions } from '../api/document'
import { userStore } from '../store/user'

const documentList = ref([])
const loading = ref(false)
const uploadDialogVisible = ref(false)
const versionDialogVisible = ref(false)
const compareDialogVisible = ref(false)
const uploading = ref(false)
const loadingVersions = ref(false)
const selectedFile = ref(null)
const uploadRef = ref(null)
const versionList = ref([])
const selectedVersions = ref([])
const compareResult = ref(null)
const activatingVersionId = ref(null)

const pagination = ref({ page: 1, size: 10, total: 0 })

const fetchDocuments = async () => {
  loading.value = true
  try {
    const response = await getDocuments(pagination.value.page, pagination.value.size)
    documentList.value = response.records || response.content || []
    pagination.value.total = response.total || 0
  } catch (error) {
    ElMessage.error('获取文档列表失败')
  } finally {
    loading.value = false
  }
}

const handleFileChange = (file) => { selectedFile.value = file.raw }

const handleUpload = async () => {
  if (!selectedFile.value) return
  const formData = new FormData()
  formData.append('file', selectedFile.value)
  formData.append('userId', userStore.getCurrentUserId())
  uploading.value = true
  try {
    await uploadDocument(formData)
    ElMessage.success('上传成功')
    uploadDialogVisible.value = false
    selectedFile.value = null
    if (uploadRef.value) uploadRef.value.clearFiles()
    fetchDocuments()
  } catch (error) {
    ElMessage.error('上传失败')
  } finally {
    uploading.value = false
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除文档"${row.fileName}"吗？`, '确认删除', { type: 'warning' })
    await deleteDocument(row.id)
    ElMessage.success('删除成功')
    fetchDocuments()
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('删除失败')
  }
}

const handleViewVersions = async (row) => {
  versionDialogVisible.value = true
  selectedVersions.value = []
  await fetchVersions(row.id)
}

const handleSelectVersionForCompare = (version) => {
  if (selectedVersions.value.length < 2) selectedVersions.value.push(version)
}

const handleRemoveVersionFromCompare = (version) => {
  const index = selectedVersions.value.findIndex(v => v.id === version.id)
  if (index > -1) selectedVersions.value.splice(index, 1)
}

const handleCompareVersions = async () => {
  if (selectedVersions.value.length !== 2) return
  try {
    compareResult.value = await compareVersions(selectedVersions.value[0].id, selectedVersions.value[1].id)
    compareDialogVisible.value = true
  } catch (error) {
    ElMessage.error('版本对比失败')
  }
}

const handlePageChange = (page) => { pagination.value.page = page; fetchDocuments() }
const handleSizeChange = (size) => { pagination.value.size = size; pagination.value.page = 1; fetchDocuments() }

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

const formatFileSize = (bytes) => {
  if (!bytes) return '-'
  const kb = bytes / 1024
  return kb < 1024 ? kb.toFixed(2) + ' KB' : (kb / 1024).toFixed(2) + ' MB'
}

const getFileTypeColor = (fileType) => {
  const typeMap = { 'pdf': 'danger', 'doc': 'primary', 'docx': 'primary', 'xls': 'success', 'xlsx': 'success', 'txt': 'warning' }
  return typeMap[fileType?.toLowerCase()] || 'info'
}

const getDocumentFileName = (documentId) => {
  const document = documentList.value.find(doc => doc.id === documentId)
  return document ? document.fileName : '未知文件'
}

const handleActivateVersion = async (version) => {
  try {
    await ElMessageBox.confirm(
      `确定要应用版本 ${version.versionNumber} 吗？这将替换当前在知识库中生效的版本。`, 
      '确认应用版本', 
      { type: 'warning' }
    )
    
    activatingVersionId.value = version.id
    
    const response = await fetch(`/api/documents/versions/${version.id}/activate`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error('版本应用失败')
    }
    
    const result = await response.json()
    
    if (result.success) {
      ElMessage.success(result.message)
      // 刷新版本列表
      await fetchVersions(version.documentId)
    } else {
      ElMessage.error(result.message || '版本应用失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('版本应用失败')
      console.error('版本应用错误:', error)
    }
  } finally {
    activatingVersionId.value = null
  }
}

const fetchVersions = async (documentId) => {
  loadingVersions.value = true
  try {
    const response = await fetch(`/api/documents/${documentId}/versions`)
    if (!response.ok) {
      throw new Error('获取版本列表失败')
    }
    versionList.value = await response.json()
  } catch (error) {
    ElMessage.error('获取版本列表失败')
    console.error('获取版本列表错误:', error)
  } finally {
    loadingVersions.value = false
  }
}

onMounted(() => { fetchDocuments() })
</script>

<style scoped>
.document-management {
  max-width: 1400px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #262626;
}

.version-compare-section {
  margin-top: 24px;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 8px;
}

.version-compare-section h4 {
  margin-bottom: 12px;
  color: #262626;
  font-size: 14px;
  font-weight: 500;
}

.compare-result {
  padding: 20px;
}

.compare-result h4 {
  margin-bottom: 12px;
  color: #262626;
  font-size: 16px;
  font-weight: 500;
}

.version-content {
  background: linear-gradient(135deg, #f6f8fb 0%, #f0f2f5 100%);
  padding: 20px;
  border-radius: 8px;
  max-height: 500px;
  overflow-y: auto;
  border-left: 4px solid #1890ff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.version-content pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  line-height: 1.8;
  color: #262626;
  font-size: 14px;
}

.el-upload {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
}

.compare-summary {
  background: #f8f9fa;
}

.differences-list {
  max-height: 300px;
  overflow-y: auto;
}

.difference-item {
  padding: 4px 0;
  border-bottom: 1px solid #eee;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.6;
}

.difference-item:last-child {
  border-bottom: none;
}

.compare-result .el-card {
  height: 600px;
}

.compare-result .version-content {
  height: 500px;
  overflow-y: auto;
}
</style>
